#!/usr/bin/perl
use strict;


# ITER = number of random iterations
# RANGE = the range of identifiers
# MATCHIN = the range of identifiers which match (i.e. subset of RANGE)

#my ($ITER, $RANGE, $MATCHING) = (100, 20, 5);
#my ($ITER, $RANGE, $MATCHING) = (200000, 5000, 250);
#my ($ITER, $RANGE, $MATCHING) = (20000000, 500000, 25000);
my ($ITER, $RANGE, $MATCHING) = (2000, 50, 5);
die unless $RANGE > $MATCHING;

print STDERR "\tGenerating test files\n";
{
	#
	#	list of matching identifiers
	#
	open IDENTIFIERS, ">identifiers.test";
	for (0..$MATCHING)
	{
		print IDENTIFIERS "id_$_\n";
		print IDENTIFIERS "id_$_\n";
	}

	#
	#	input file to filter
	#
	open RESULTS, ">results.test";
	print RESULTS "seq1\tseq2\n----\t----\n";
	print RESULTS "\n";

	#
	#	expected results of filtering
	#
	open BOTH, 		">both.matches";
	open EITHER,	">either.matches";
	open ONE, 		">one.matches";
	open NEITHER,	">neither.matches";
		
	my $cnt_results = 0;
	print STDERR "\t[";
	my $EXTRA_MATCHING = '';
	for (0..$ITER)
	{
		
		print STDERR "." if ($_ % ($ITER / 50) == 0);
		++$cnt_results;
		my $id1 =  int(rand($RANGE));
		my $id2 =  int(rand($RANGE));
	
		# add first row
		if ($_ == 0)
		{
		    print IDENTIFIERS "id_$id1\n";
		    $EXTRA_MATCHING = $id1;
		}
		my $cnt_matches = 0;
		$cnt_matches++  if ($id1 == $EXTRA_MATCHING || $id1 <= $MATCHING);
		$cnt_matches++  if ($id2 == $EXTRA_MATCHING || $id2 <= $MATCHING);
		
		
	
		my $line = "id_$id1\tid_$id2\tresult $cnt_results\n";
		print RESULTS $line;
		if ($cnt_matches == 0)
		{
			print NEITHER $line;
		}
		elsif ($cnt_matches == 1)
		{
			print ONE $line ;
			print EITHER $line ;
		}
		else
		{
			print BOTH $line ;
			print EITHER $line ;
		}
	}
	print STDERR "]\n";
}

print STDERR "\tRunning seq_pairs_filter_by_identifier\n";
system("seq_pairs_filter_by_identifier -v --matching_identifiers identifiers.test ".
		" -i results.test ".
		"--both both.matches.test ".
		"--either either.matches.test ".
		"--neither neither.matches.test ".
		"--one one.matches.test");
print STDERR "\tComparing results...\n";
for my $file(qw (both.matches either.matches neither.matches one.matches))
{
	my @diff = `diff $file $file.test`;
	if (@diff != 0)
	{
		print STDERR "FAILED: $file $file.test are not the same!\n";
		exit;
	}
}
print STDERR "\tCleaning up...\n";
unlink (glob("*.test"));
unlink (glob("*.matches"));
print STDERR "\n\tSUCCESS!!!\n\n";

